import pygame


class Scoreboard:
    """显示得分"""
    def __init__(self, stats):
        """初始化显示得分涉及的属性"""
        self.stats = stats
        self.screen = self.stats.ai.screen
        self.text_color = (30, 30, 30)
        self.font = pygame.font.SysFont(None, 40)
        # 准备得分图像
        self.prep_score()
        self.prep_high_score()
        self.prep_level()
        self.stats.prep_ships()

    def prep_score(self):
        """将得分渲染为一幅图像"""
        # 四舍五入,-1：舍入到10的整数倍
        rounded_score = round(self.stats.score, -1)
        score_str = "{:,}".format(rounded_score)
        self.score_img = self.font.render(score_str, True, self.text_color)
        self.score_rect = self.score_img.get_rect()
        self.score_rect.right = self.screen.get_rect().right - 20
        self.score_rect.top = 20

    def prep_high_score(self):
        """将最高得分渲染为一幅图像"""
        # 四舍五入,-1：舍入到10的整数倍
        rounded_score = round(self.stats.high_score, -1)
        score_str = "Highest:" + "{:,}".format(rounded_score)
        self.high_score_img = self.font.render(score_str, True,
                                               self.text_color)
        self.high_score_rect = self.high_score_img.get_rect()
        self.high_score_rect.centerx = self.screen.get_rect().centerx
        self.high_score_rect.top = 20

    def prep_level(self):
        """将等级渲染为图像"""
        level_str = str(f"Level {self.stats.level}")
        self.level_img = self.font.render(level_str, True, self.text_color)
        self.level_rect = self.level_img.get_rect()
        self.level_rect.right = self.score_rect.right
        self.level_rect.top = self.score_rect.bottom + 10

    def show_score(self):
        """在屏幕上显示得分和等级"""
        self.screen.blit(self.score_img, self.score_rect)
        self.screen.blit(self.high_score_img, self.high_score_rect)
        self.screen.blit(self.level_img, self.level_rect)
        self.stats.ships.draw(self.screen)

    def check_high_score(self):
        """检查是否诞生了新的最高分"""
        if self.stats.score > self.stats.high_score:
            self.stats.high_score = self.stats.score
            self.prep_high_score()
